/**
 * 
 */
package com.yunyike.controller.merchandise;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yunyike.constants.CommonConstant;
import com.yunyike.constants.RequestConstant;
import com.yunyike.constants.ResponseConstant;
import com.yunyike.controller.BaseController;
import com.yunyike.dto.CartDTO;
import com.yunyike.dto.MerchandiseSearchDTO;
import com.yunyike.exception.BadRequestException;
import com.yunyike.model.Merchandise;
import com.yunyike.model.User;
import com.yunyike.response.Response;
import com.yunyike.service.IMerchandiseService;
import com.yunyike.service.IShopService;
import com.yunyike.utils.mybatis.PageBean;

/**
 * @author zhengqiang.shi
 * 2015年11月18日 下午8:51:15
 */
@Controller
@RequestMapping(value=RequestConstant.MERCHANDISE)
public class MerchandiseController extends BaseController{

	private Logger log = LoggerFactory.getLogger(MerchandiseController.class);
	
	@Autowired
	private IMerchandiseService merchandiseService;
	
	@Autowired
	private IShopService shopService;
	
//	@Autowired
//	private ICartService2 cartService;
	
	@Value("${itemPageSize}")
	private int itemPageSize;
	
	/**
	 * 获取店铺的商品信息
	 * @param shopId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.SHOP+"/{shopId}")
	public void findMerchandiseByShopId(@PathVariable String shopId,HttpServletRequest request,
			HttpServletResponse response,Model model,Integer pageSize,Integer page){
		// response object
		Response res = new Response();
		
		// 查询店铺的商品
		PageBean<String> pageBean = new PageBean<String>();
		pageBean.setParameter(shopId);
		pageBean.setPage(page == null ? CommonConstant.NUMBER_1 : page);
		if(pageSize != null && pageSize > 0){
			pageBean.setPageSize(pageSize);
		}
		List<Merchandise> merchandises;
		try {
			merchandises = merchandiseService.findMerchandiseByShop(pageBean);
		} catch (Exception e) {
			log.error("merchandiseService.findMerchandiseByShop has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		if(merchandises == null || merchandises.isEmpty()){
			log.info("merchandiseService.findMerchandiseByShop return null.");
			res.getResult().setCode(CommonConstant.NUMBER__2);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__2));
			returnDatas(res, response);
			return;
		}
		
		res.setData(merchandises);
		returnDatas(res, response);
		return;
	}
	
	/**
	 * 获取分类下的商品信息
	 * @param shopId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.CATEGORY+"/{categoryId}")
	public void findMerchandiseByCategoryId(@PathVariable String categoryId,HttpServletRequest request,
			HttpServletResponse response,Model model,Integer pageSize,Integer page,String newItem,String price){
		
		// response object
		Response res = new Response();
		
		MerchandiseSearchDTO msd = new MerchandiseSearchDTO();
		msd.setCategoryId(categoryId);
		
		if(StringUtils.isNotBlank(newItem)){
			msd.setNewItem(newItem);
		}
		
		if(StringUtils.isNotBlank(price)){
			msd.setOrderByPrice(price);
		}
		
		log.info(msd.toString());
		
		// 查询店铺的商品
		PageBean<MerchandiseSearchDTO> pageBean = new PageBean<MerchandiseSearchDTO>();
		pageBean.setParameter(msd);
		pageBean.setPage(page == null ? CommonConstant.NUMBER_1 : page);
		if(pageSize != null && pageSize > 0){
			pageBean.setPageSize(pageSize);
		}
		List<Merchandise> merchandises;
		try {
			merchandises = merchandiseService.findMerchandiseByCondition(pageBean);
		} catch (Exception e) {
			log.error("merchandiseService.findMerchandiseByCondition has error.message:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		if(merchandises == null || merchandises.isEmpty()){
			log.info("no record by findMerchandiseByCondition,categoryId:{}",categoryId);
			res.getResult().setCode(CommonConstant.NUMBER__2);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__2));
			returnDatas(res, response);
			return;
		}
		
		res.setData(merchandises);
		returnDatas(res, response);
		return;
	}
	
	/**
	 * 获取品牌下的商品信息
	 * @param shopId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.MERCHANDISE_BRAND+"/{brandId}")
	public void findMerchandiseByBrandId(@PathVariable String brandId,HttpServletRequest request,
			HttpServletResponse response,Model model,Integer pageSize,Integer page,String newItem,String price){
		
		// response object
		Response res = new Response();
		
		MerchandiseSearchDTO msd = new MerchandiseSearchDTO();
		msd.setBrandId(brandId);
		
		if(StringUtils.isNotBlank(newItem)){
			msd.setNewItem(newItem);
		}
		
		if(StringUtils.isNotBlank(price)){
			msd.setOrderByPrice(price);
		}
		
		log.info(msd.toString());
		
		// 查询店铺的商品
		PageBean<MerchandiseSearchDTO> pageBean = new PageBean<MerchandiseSearchDTO>();
		pageBean.setParameter(msd);
		pageBean.setPage(page == null ? CommonConstant.NUMBER_1 : page);
		if(pageSize != null && pageSize > 0){
			pageBean.setPageSize(pageSize);
		}
		List<Merchandise> merchandises;
		try {
			merchandises = merchandiseService.findMerchandiseByCondition(pageBean);
		} catch (Exception e) {
			log.error("merchandiseService.findMerchandiseByCondition has error.message:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		if(merchandises == null || merchandises.isEmpty()){
			log.info("no record by findMerchandiseByCondition,brandId:{}",brandId);
			res.getResult().setCode(CommonConstant.NUMBER__2);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__2));
			returnDatas(res, response);
			return;
		}
		
		res.setData(merchandises);
		returnDatas(res, response);
		return;
	}
	
	/****************************************以上为最新增加*********************************************/
	/**
	 * 商品详情
	 * @param id
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/{id}")
	public void merchandiseDetail(@PathVariable(value="id") String id, Model model,
			HttpServletResponse response){
		
		// response object
		Response res = new Response();
		
		log.info("to merchandise detail.id:"+id);
		
		Merchandise merchandise;
		try {
			merchandise = merchandiseService.findMerchandiseByNumber(id);
		} catch (Exception e) {
			log.error("merchandiseService.findMerchandiseByNumber has error.message:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		if(merchandise == null){
			log.error("not found merchandise info.id:"+id);
			res.getResult().setCode(CommonConstant.NUMBER__2);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__2));
			returnDatas(res, response);
			return;
		}
		
		res.setData(merchandise);
		returnDatas(res, response);
		return;
	}
	
	/**
	 * 根据商品条码获取商品信息
	 */
	/*@ResponseBody
	@RequestMapping(value=RequestConstant.MERCHANDISE_FIND_BY_BARCODE+"/{itemBarCode}")
	public String findMerchandiseByBarCode(@PathVariable String itemBarCode){
		
		if(StringUtils.isBlank(itemBarCode)){
			log.info("findMerchandiseByBarCode itemBarCode is blank.");
//			return ResponseConstant.MERCHANDISE_NOT_FOUND;
			return "";
		}
		
		Merchandise merchandise = merchandiseService.findMerchandiseByBarCode(itemBarCode);
		if(merchandise == null){
			log.info("findMerchandiseByBarCode no merchandise by BarCode {}",itemBarCode);
//			return ResponseConstant.MERCHANDISE_NOT_FOUND;
			return "";
		}
		
		log.info("find the merchandise by barcode {}",itemBarCode);
//		return ResponseConstant.REDIRECT+RequestConstant.MERCHANDISE+
//				"/"+merchandise.getMerchandiseNumber()+RequestConstant.MERCHANDISE_SUFFIX;
		return merchandise.getMerchandiseNumber();
	}*/
	
	/**
	 * 查询某店铺的所有商品
	 * @param id
	 * @param model
	 * @return
	 */
	/*@ResponseBody
	@RequestMapping(value=RequestConstant.MERCHANDISE_SEARCH+"/{shopId}/{page}")
	public String pageListByShopId(@PathVariable String shopId,@PathVariable Integer page,
			HttpServletResponse response,Model model){
		
		log.info("find item... shopId:{},page:{}",shopId,page);
		
		if(StringUtils.isBlank(shopId)){
			log.info("pageListByShopId , shopId is null.");
			return null;
		}
		
		if(page == null || page < 1){
			page = 1;
		}
		
		PageBean<String> pageBean = new PageBean<String>();
		pageBean.setParameter(shopId);
		pageBean.setPage(page);
		pageBean.setPageSize(itemPageSize);
		List<Merchandise> list = merchandiseService.findMerchandiseByShop(pageBean);
		
		String itemsJson = JsonUtils.ObjectAsString(list);
		
		response.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
		try {
			PrintWriter writer = response.getWriter();
			writer.write(itemsJson);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			log.error("response.getWriter().write error."+e.getMessage(),e);
			return null;
		}
		
		return null;
	}*/
	
	/**
	 * 查询某店铺的商品 根据重量
	 * @param id
	 * @param model
	 * @return
	 */
	/*@RequestMapping(value=RequestConstant.MERCHANDISE_SEARCH_BY_CONDITION+"/{shopId}/{weight}")
	public String listByShopIdAndWeight(@PathVariable(value="shopId") String shopId,@PathVariable Double weight, Model model){
		
		if(StringUtils.isBlank(shopId) || weight == null){
			throw new BadRequestException("request param not correct.");
		}
		
		log.info("find shop... shopId:"+shopId);
		Shop shop = shopService.findShopById(shopId);
		
		if(shop == null){
			throw new BadRequestException("request param not correct.");
		}
		
		model.addAttribute("shop", shop);
		
		log.info("find merchandise by condition ....");
		List<Merchandise> list = merchandiseService.findMerchandiseByCondition(shopId, weight);
		
		model.addAttribute("merchandiseList", list);
		
		return ResponseConstant.MERCHANDISE_LIST_BY_CONDITION;
	}*/
	
	/**
	 * 查询当前结算的商品
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value=RequestConstant.MERCHANDISE_FIND_SETTLEMENT+"/{shopId}")
	public String findSettlementItems(@PathVariable(value="shopId") String shopId, Model model){
		
		if(StringUtils.isBlank(shopId)){
			throw new BadRequestException("request param not correct.");
		}
		
		log.info("findSettlementItems... shopId:"+shopId);
		
		User user = getCurrentUser();
		
		CartDTO cartDTO = null;
		
		model.addAttribute("cartSkuDTOList", cartDTO.getCartSkuDTOList());
		
		log.info("findSettlementItems end.");
		
		return ResponseConstant.MERCHANDISE_LIST_BY_SETTLEMENT;
	}
}
